﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.ComponentModel;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.Phone;
using Microsoft.Phone.Controls;
using Hawaii.Services.Client;
using Hawaii.Services.Client.Relay;

namespace PhoneApp1
{
    public partial class ManageGroups : PhoneApplicationPage
    {
        public ManageGroups()
        {
            InitializeComponent();
            Loaded += new RoutedEventHandler(ManageGroups_Loaded);
        }

        /// <summary>
        /// Gets the relay data context.
        /// </summary>
        private RelayContext RelayContext
        {
            get { return ((App)App.Current).RelayContext; }
        }

        private void ManageGroups_Loaded(object sender, RoutedEventArgs e)
        {
            this.Refresh_Created_List();
 //           this.Refresh_Maxmember_List();
        }

        /// <summary>
        /// Button handler for creating a group
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Creategroup_Click(object sender, RoutedEventArgs e)
        {
            if (this.Name_Textbox.Text == "")
            {
                this.DisplayMessage("You must enter a group name", "Error");
            }
            else if(this.Number_Textbox.Text == "")
            {
                this.DisplayMessage("You must enter a maximum members", "Error");
            }
            else
            {
                RelayService.CreateGroupAsync(HawaiiClient.HawaiiApplicationId,
                                              this.OnCompleteCreateGroup);

                NavigationService.Navigate(new Uri("/ManageGroups.xaml", UriKind.Relative));
            }
        }

        /// <summary>
        ///  Call back routine for completion of joining  a group
        /// </summary>
        /// <param name="result"></param>
        private void OnCompleteCreateGroup(GroupResult result)
        {
            Debug.Assert(result != null, "result is null");

            if (result.Status == Status.Success)
            {
                // add the newly created group to the list of groups for this Relay Context
                this.RelayContext.Groups.Add(result.Group);

                /* save this created group in the phone's file storage */
                ((App)App.Current).fileStorage.df.created_groups.Add(result.Group.RegistrationId);

                /* Save the group name with the relay context */
                this.Dispatcher.BeginInvoke(
                   delegate
                   {
                       result.Group.Name = this.Name_Textbox.Text;
                       result.Group.Max_Number = this.Number_Textbox.Text;
                       this.Name_Textbox.Text = "";
                       this.Number_Textbox.Text = "";
                       this.Refresh_Created_List();
      //                 this.Refresh_Maxmember_List();
                       this.DisplayMessage("Group " + result.Group.Name + " has been created", "Group Message");
                   });

            }
            else
            {
                // Display a message box, in case of any error creating a new endpoint.
                this.DisplayMessage("Error creating app group.", "Error");
            }

        }

        private void Refresh_Created_List()
        {
            List<PollGroup> groupList = new List<PollGroup>();

            foreach (string group_id in ((App)App.Current).fileStorage.df.created_groups)
            {
                Group group = this.RelayContext.Groups.Find(group_id);
                groupList.Add(new PollGroup(group.Name, group.RegistrationId, group.Max_Number));
            }

            this.created_group_list.ItemsSource = groupList;
            this.max_member_list.ItemsSource = groupList;
        }

   /*     private void Refresh_Maxmember_List()
        {
            List<PollGroup> groupList = new List<PollGroup>();

            foreach (string group_id in ((App)App.Current).fileStorage.df.created_groups)
            {
                Group group = this.RelayContext.Groups.Find(group_id);
                groupList.Add(new PollGroup(group.Name, group.RegistrationId));
            }

            this.max_member_list.ItemsSource = groupList;
          
        }*/

        /// <summary>
        /// Helper method to display messages.
        /// </summary>
        /// <param name="message">A valid message.</param>
        /// <param name="caption">A valid caption.</param>
        private void DisplayMessage(string message, string caption)
        {
            this.Dispatcher.BeginInvoke(
                    delegate
                    {
                        MessageBox.Show(message, caption, MessageBoxButton.OK);
                    });
        }

        private void delete_group_Click(object sender, RoutedEventArgs e)
        {
            PollGroup group_item = (PollGroup)this.created_group_list.SelectedItem;
            if (group_item == null)
            {
                this.DisplayMessage("No group was selected", "Error");
                return;
            }

            Group group = this.RelayContext.Groups.Find(group_item.Registration_ID);
            if (group == null)
            {
                this.DisplayMessage("No group is selected in the list box.", "Error");
                return;
            }

            RelayService.DeleteGroupAsync(HawaiiClient.HawaiiApplicationId,
                                          group,
                                          this.OnCompleteDeleteGroup,
                                          group);
        }

        /// <summary>
        /// Callback method for deleting a group.
        /// </summary>
        /// <param name="result">Result object from service.</param>
        private void OnCompleteDeleteGroup(GroupResult result)
        {
            Debug.Assert(result != null, "result is null");

            if (result.Status == Status.Success)
            {
                // Get the group object which we passed through DeleteGroupAsync method
                Group group = (Group)result.StateObject;
                Debug.Assert(group != null, "StateObject is null");

                // Remove the group from available groups object.
                this.RelayContext.Groups.Remove(group.RegistrationId);

                // Remove the group from groups container of MyEndpoint.
                if (this.RelayContext.Endpoint.Groups.Exists(group.RegistrationId))
                {
                    this.RelayContext.Endpoint.Groups.Remove(group.RegistrationId);
                }

                ((App)App.Current).fileStorage.df.created_groups.Remove(group.RegistrationId);

                // We just updated the data. Refresh it
                this.Dispatcher.BeginInvoke(
                    delegate
                    {
                        this.DisplayMessage("You have deleted the group " + group.Name, "Group Message");
                        this.Refresh_Created_List();
        //                this.Refresh_Maxmember_List();
                    });
            }

            else
            {
                this.DisplayMessage("Deleting a group failed.", "Error");
            }
        }


        private void Join_button_Click(object sender, RoutedEventArgs e)
        {
            if (this.RelayContext.Endpoint == null)
            {
                this.DisplayMessage("Invalid Endpoint, restart application", "Error");
                return;
            }

            PollGroup group_item = (PollGroup)this.created_group_list.SelectedItem;
            if (group_item == null)
            {
                this.DisplayMessage("No group was selected", "Error");
                return;
            }

            Group group = this.RelayContext.Groups.Find(group_item.Registration_ID);
            if (group == null)
            {
                this.DisplayMessage("No group is selected in the list box.", "Error");
                return;
            }

            RelayService.JoinGroupAsync(HawaiiClient.HawaiiApplicationId,
                                        this.RelayContext.Endpoint,
                                        group,
                                        this.OnCompleteJoinGroup,
                                        group);
        }

        private void OnCompleteJoinGroup(GroupResult result)
        {
            Debug.Assert(result != null, "result is null");

            if (result.Status == Status.Success)
            {
                Group group = (Group)result.StateObject;
                Debug.Assert(group != null, "StateObject is null");

                this.RelayContext.Endpoint.Groups.Add(group);

                this.Dispatcher.BeginInvoke(
                    delegate
                    {
                        this.Refresh_Created_List();
                    });

                this.DisplayMessage("You have joined group " + group.Name, "Groups Update");
            }
            else
            {
                this.DisplayMessage("You are already a member of this group", "Error");
            }
        }

        private void get_id_Click(object sender, RoutedEventArgs e)
        {
            if (this.RelayContext.Endpoint == null)
            {
                this.DisplayMessage("Invalid Endpoint, restart application", "Error");
                return;
            }

            PollGroup group_item = (PollGroup)this.created_group_list.SelectedItem;
            if (group_item == null)
            {
                this.DisplayMessage("No group was selected", "Error");
                return;
            }

            this.DisplayMessage("Group " + group_item.Name + " has Registration ID: " + group_item.Registration_ID, "Group ID");
        }


        private void button1_Click(object sender, RoutedEventArgs e)
        {
            NavigationService.GoBack();
        }

    }
}
